<?php
/**
 * Fake4
 * @copyright   Copyright(c) 2024-2034
 * @author      tianjie <527707665@qq.com>
 * @link        http://www.tinphp.com/
 */

namespace app\middleware;

use ReflectionClass;
use ReflectionException;
use tian\MiddlewareInterface;
use tian\Response;
use tian\Request;

class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param $next
     * @return Response
     */
    public function handle(Request $request, $next): Response
    {
        try {
            $action = $request->action();
            $controllerClass = $request->controllerClass();

            // 通过反射获取控制器哪些方法不需要登录
            $controller = new ReflectionClass($controllerClass);
            $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

            // 访问的方法需要登录验证
            if (!in_array($action, $noNeedLogin)) {
                $authorization = trim($request->header('authorization') ?: "");
                if (!$authorization) {
                    return json(['code' => -1, 'msg' => '未登录']);
                }
            }
            //不需要登录
            return $next($request);
        } catch (ReflectionException $e) {
            setLog('302 错误：' . $e->getMessage());
            return json(['code' => 302, 'msg' => '页面路径不存在']);
        }
    }
}
